package com.imoblife.brainwavestus.customview;

import java.util.ArrayList;
import java.util.List;

import com.imoblife.brainwavestus.R;

import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class MenuList {

	class MenuItem {
		String _content;
		Runnable _event;

		public MenuItem(String content, Runnable event) {

			_event = event;
			_content = content;

		}
	}

	List<MenuItem> _menuItems;

	View _view;
	Activity _activity;

	public MenuList(View view, Activity activity) {
		_view = view;
		_menuItems = new ArrayList<MenuList.MenuItem>();
		_activity = activity;
	}

	public void addItem(String itemContent, Runnable itemEvent) {
		_menuItems.add(new MenuItem(itemContent, itemEvent));
	}

	public void display() {

		final ListView listView = (ListView) _activity.getLayoutInflater()
				.inflate(R.layout.menu_dialog, null);

		final BaseAdapter baseAdapter = new BaseAdapter() {

			public View getView(int position, View convertView, ViewGroup parent) {

				if (convertView == null) {
					convertView = _activity.getLayoutInflater().inflate(
							R.layout.menu_item, null);
				}

				TextView item = (TextView) convertView;

				item.setText(_menuItems.get(position)._content);

				return item;
			}

			public long getItemId(int position) {
				// TODO Auto-generated method stub
				return 0;
			}

			public Object getItem(int position) {
				// TODO Auto-generated method stub
				return null;
			}

			public int getCount() {
				// TODO Auto-generated method stub
				return _menuItems.size();
			}
		};

		float ds = _activity.getResources().getDisplayMetrics().density;

		int w = (int) (200 * ds);

		final PopupWindow pm = new PopupWindow(listView, w, -2);
		pm.setFocusable(true);
		pm.setBackgroundDrawable(_activity.getResources().getDrawable(
				R.drawable.menu_back));

		pm.showAsDropDown(_view, -(int) (1 * ds), (int) (1 * ds));

		listView.setAdapter(baseAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				_menuItems.get(arg2)._event.run();
				pm.dismiss();
			}
		});
		pm.setOutsideTouchable(true);

	}
}
